package com.djinfo.work.controller;


import com.alibaba.fastjson.JSONObject;
import com.djinfo.work.common.anno.Login;
import com.djinfo.work.common.enums.Action;
import com.djinfo.work.entity.TbSysMenu;
import com.djinfo.work.entity.TbSysRoles;
import com.djinfo.work.entity.TbSysUsers;
import com.djinfo.work.service.LogService;
import com.djinfo.work.service.MenuService;
import com.djinfo.work.service.RoleService;
import com.djinfo.work.service.UserService;
import com.djinfo.work.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * 登录控制器
 * @author Gaojun.Zhou
 * @date 2016年12月14日 下午2:54:01
 */
@Controller
@RequestMapping("/")
public class LoginController{
    
	/**
	 * 用户服务
	 */
	@Autowired
    private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private MenuService menuService;
	/**
	 * 日志服务
	 */
	@Autowired
    private LogService logService;

	@RequestMapping("/index.do")
	public String index(){
		return "index1.html";
	}
	/**
	 * 执行登录
	 */
	@Login(action=Action.Skip)
	@ResponseBody
	@RequestMapping("/login.do")
	public JSONObject login(String username, String password, String captcha,
							HttpSession session,
							HttpServletRequest request) {
		// json格式
		JSONObject data = new JSONObject();
		// 将map存入json格式中 返回前台
		Map<String, Object> result = new HashMap<String, Object>();
		// 查询用户ID
		String md5Password=MD5Utils.GetMD5Code(password);
		String wdUser = userService.getUserID(username, md5Password);
		/*String a = null;
		a.equals("88");*/
		// 如果用户不存在，则返回0
		if ("".equals(wdUser)) {
			// 登录失败的返回信息
			data.put("resultcode", 203);
			data.put("reason", "用户名或者密码错误");
			return data;
		}
		// 获取验证码
		/*String sRand = (String) session.getAttribute("randCheckCode");
		if(sRand==null||sRand==""){
			data.put("resultcode", 204);
			data.put("reason", "验证码错误");
			return data;
		}
		// 转换大小写
		String sRands = sRand.toLowerCase();
		// 转换大小写
		String authCodes = captcha.toLowerCase();
		if (!sRands.equals(authCodes)) {
			data.put("resultcode", 205);
			data.put("reason", "验证码错误");
			return data;
		}*/
		// 用户验证通过
		if (!"".equals(wdUser)) {
			// 存储数据与前台交互
			TbSysUsers tbSysUsers = userService.get(wdUser);
			data.put("resultcode", 200);
			data.put("reason", "登陆成功");
			data.put("token", "xxxxxxx");
			result.put("userID", tbSysUsers.getPkUserId());
			result.put("username", tbSysUsers.getUserName());
			result.put("headImg", "images/user.jpg");
			data.put("result", result);
			// 给session赋值
			if (session.getAttribute("userId") != null) {
				// 如果session有值 就删掉重新保存
				session.removeAttribute("userId");
				session.setAttribute("userId", tbSysUsers.getPkUserId());
				// 如果session有值 就删掉重新保存
				session.removeAttribute("username");
				session.setAttribute("username", tbSysUsers.getUserName());
			} else {
				// 如果没有值，就保存用户id
				session.setAttribute("userId", tbSysUsers.getPkUserId());
				session.setAttribute("username",tbSysUsers.getUserName());
			}
//			getUserMenus(tbSysUsers.getPkUserId(),session);
		}

		return data;
	}
	@ResponseBody
	@RequestMapping("/getMenus.do")
	public JSONObject getUserMenus(HttpSession session){
		JSONObject data = new JSONObject();
		List menusList = (List)session.getAttribute("menusList");
		if(menusList!=null){
			data.put("menusList",menusList);
			return data;
		}
		java.util.List<String> menuIds = null;
		String userId = (String) session.getAttribute("userId");
		java.util.List<TbSysRoles> myRoles = userService.getUserRoles(userId);
		menuIds = roleService.getMenuList(myRoles.get(0).getPkRoleId());
		java.util.List<TbSysMenu> menuList = new ArrayList<>();
		for (String menuId: menuIds) {
			TbSysMenu menu = menuService.getMenuById(menuId);
			if(menu==null){continue;}
			menuList.add(menu);
		}

		session.setAttribute("menusList",menuList(menuList));
		data.put("menusList",menuList(menuList));
		List list4=menuList(menuList);
		return data;
	}


	private List menuList(java.util.List<TbSysMenu> menuList) {

		java.util.List<Map<String, Object>> resultlist2 = new ArrayList<Map<String, Object>>();
		Map<String, Object> resultmap = null;
		Map<String, Object> resultmap2 = null;
		Map<String, Object> resultmap3 = null;

//		// 查询level列为0的全部信息 ---为父节点
//		List<TbSysMenu> tdyalist = UserService.authoritiesfindAll(0);
		// 循环外层--父节点
		for (TbSysMenu list : menuList) {
			java.util.List<Map<String, Object>> resultlist3 = new ArrayList<Map<String, Object>>();
			resultmap = new HashMap<String, Object>();
			// 将父节点name属性存近map
			if(list.getParentAuthId().equals("0")){
				resultmap.put("name", list.getMenuName());
			}else {
				continue;
			}
			// 循环内层与其父节点对应的子节点
			for (TbSysMenu list2 : menuList) {

				// 将子节点存进map2
				if(list2.getParentAuthId().equals(list.getPkMenuId())){
					resultmap2 = new HashMap<String, Object>();
					resultmap2.put("name", list2.getMenuName());
					if(list2.getIsLeaf().equals("1")){
						resultmap2.put("url", list2.getPageUrl());
					}else{
						java.util.List<Map<String, Object>> resultlist4 = new ArrayList<Map<String, Object>>();
						//第三层菜单 写死 有空写成递归
						for (TbSysMenu list3 : menuList) {
							if(list3.getParentAuthId().equals(list2.getPkMenuId())){
								resultmap3 = new HashMap<String, Object>();
								resultmap3.put("name", list3.getMenuName());
								resultmap3.put("url", list3.getPageUrl());
								resultlist4.add(resultmap3);
								resultmap2.put("subMenu", resultlist4);
							}
						}
					}

					resultlist3.add(resultmap2);
					resultmap.put("subMenu", resultlist3);
				}

			}

			resultlist2.add(resultmap);
		}

		return resultlist2;
	}
	/**
	 * 退出系统
	 * @return
	 * @throws IOException
	 */
	@Login(action=Action.Skip)
    @RequestMapping(value = "/logout")
    public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
		request.getSession().removeAttribute("userId");
		request.getSession().removeAttribute("menusList");
		response.sendRedirect("login.html");
		/*logService.insertLog("用户退出系统",st!=null?st.getUname():"***",request.getRequestURI(),"******");*/
    }  


	public Color getRandColor(int s, int e) {
		Random random = new Random();
		if (s > 255)
			s = 255;
		if (e > 255)
			e = 255;
		int r = s + random.nextInt(e - s);
		int g = s + random.nextInt(e - s);
		int b = s + random.nextInt(e - s);
		return new Color(r, g, b);
	}
	@Login(action=Action.Skip)
	@RequestMapping("/captcha.do")
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 禁止缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		// 指定生成的响应是图片
		response.setContentType("image/jpeg");
		int width = 200;
		int height = 60;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 创建BufferedImage类的对象
		Graphics g = image.getGraphics(); // 创建Graphics类的对象
		Graphics2D g2d = (Graphics2D) g; // 通过Graphics类的对象创建一个Graphics2D类的对象
		Random random = new Random(); // 实例化一个Random对象
		Font mFont = new Font("华文宋体", Font.BOLD, 44); // 通过Font构造字体
		g.setColor(getRandColor(200, 250)); // 改变图形的当前颜色为随机生成的颜色
		g.fillRect(0, 0, width, height); // 绘制一个填色矩形

		// 画一条折线
		BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); // 创建一个供画笔选择线条粗细的对象
		g2d.setStroke(bs); // 改变线条的粗细
		g.setColor(Color.GRAY); // 设置当前颜色为预定义颜色中的深灰色
		int[] xPoints = new int[3];
		int[] yPoints = new int[3];
		for (int j = 0; j < 3; j++) {
			xPoints[j] = random.nextInt(width - 1);
			yPoints[j] = random.nextInt(height - 1);
		}
		g.drawPolyline(xPoints, yPoints, 3);
		// 生成并输出随机的验证文字
		g.setFont(mFont);
		String sRand = "";
		int itmp = 0;
		for (int i = 0; i < 4; i++) {
			if (random.nextInt(2) == 1) {
				itmp = random.nextInt(26) + 65; // 生成A~Z的字母
			} else {
				itmp = random.nextInt(10) + 48; // 生成0~9的数字
			}
			char ctmp = (char) itmp;
			sRand += String.valueOf(ctmp);
			Color color = new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110));
			g.setColor(color);
			/**** 随机缩放文字并将文字旋转指定角度 **/
			// 将文字旋转指定角度
			Graphics2D g2d_word = (Graphics2D) g;
			AffineTransform trans = new AffineTransform();
			trans.rotate(random.nextInt(15) * 3.14 / 180, 15 * i + 10, 7);
			// 缩放文字
			float scaleSize = random.nextFloat() + 0.8f;
			if (scaleSize > 1.1f)
				scaleSize = 1f;
			trans.scale(scaleSize, scaleSize);
			g2d_word.setTransform(trans);
			/************************/
			g.drawString(String.valueOf(ctmp), 30 * i + 50, 30);

		}
		// 将生成的验证码保存到Session中
		HttpSession session = request.getSession(true);
		session.setAttribute("randCheckCode", sRand);
		g.dispose();
		ImageIO.write(image, "jpg", response.getOutputStream());
	}
}
